# frozen_string_literal: true

module VulnerabilityExports
  module Exporters
    class CsvService
      IDENTIFIER_DELIMITER = '; '
      IDENTIFIER_FORMATTER = -> (v) { v&.other_identifier_values&.to_csv(col_sep: IDENTIFIER_DELIMITER, row_sep: '') }
      # to be removed with https://gitlab.com/gitlab-org/gitlab/-/issues/412114
      NIL_FORMATTER = -> (_) { nil }

      attr_reader :vulnerabilities

      def initialize(vulnerabilities)
        @vulnerabilities = vulnerabilities
      end

      def generate(&block)
        csv_builder.render(&block)
      end

      private

      def csv_builder
        @csv_builder ||= CsvBuilder.new(vulnerabilities, mapping)
      end

      def mapping
        {
          s_('VulnerabilityExport|Group Name') => 'group_name',
          s_('VulnerabilityExport|Project Name') => 'project_name',
          s_('VulnerabilityExport|Tool') => 'report_type',
          s_('VulnerabilityExport|Scanner Name') => 'finding_scanner_name',
          s_('VulnerabilityExport|Status') => 'state',
          s_('VulnerabilityExport|Vulnerability') => 'title',
          s_('VulnerabilityExport|Details') => 'finding_description',
          s_('VulnerabilityExport|Additional Info') => NIL_FORMATTER,
          s_('VulnerabilityExport|Severity') => 'severity',
          s_('VulnerabilityExport|CVE') => 'cve_value',
          s_('VulnerabilityExport|CWE') => 'cwe_value',
          s_('VulnerabilityExport|Other Identifiers') => IDENTIFIER_FORMATTER,
          s_('VulnerabilityExport|Detected At') => 'created_at',
          s_('VulnerabilityExport|Location') => 'location',
          s_('VulnerabilityExport|Activity') => 'resolved_on_default_branch',
          s_('VulnerabilityExport|Comments') => 'notes_summary',
          s_('VulnerabilityExport|Full Path') => 'full_path'
        }
      end
    end
  end
end

VulnerabilityExports::Exporters::CsvService.prepend_mod
